import { computed, nextTick, ref, watch } from 'vue'

export default function useFixed (props) {
  const groupRef = ref(null)
  const listHeights = ref([])
  const scrollY = ref(0)
  const currentIndex = ref(0)
  // 标题固定层顶上动画
  const TITLE_HEIGHT = 30
  const distance = ref(0)

  watch(
    () => props.data,
    async () => {
      await nextTick()
      calculate()
    }
  )
  // 滚动时触发
  /**
   * 假设 listHeights 的值为 [0, 100, 250, 400]，表示有三个组的高度区间分别为：
   *
   * 第一组：[0, 100)
   * 第二组：[100, 250)
   * 第三组：[250, 400)
   * 如果 scrollY 的值为 150，那么 newY 会在第二组的高度区间内，因此 currentIndex 会被设置为 1。
   */
  watch(scrollY, newY => {
    const listHeightsVal = listHeights.value
    for (let i = 0; i < listHeightsVal.length - 1; i++) {
      const heightTop = listHeightsVal[i]
      const heightBottom = listHeightsVal[i + 1]
      if (newY >= heightTop && newY <= heightBottom) {
        currentIndex.value = i
        distance.value = heightBottom - newY
      }
    }
  })

  const fixedTitle = computed(() => {
    if (scrollY.value < 0) {
      return ''
    }
    // 当前组
    const currentGroup = props.data[currentIndex.value]
    return currentGroup ? currentGroup.title : ''
  })
  const fixedStyle = computed(() => {
    // distanceVal < TITLE_HEIGHT 代表下一组已经进入，动画开始生效
    // transform: translate(0px, 0px);
    const distanceVal = distance.value
    const diff = distanceVal > 0 && distanceVal < TITLE_HEIGHT ? distanceVal - TITLE_HEIGHT : 0
    return {
      transform: `translate(0,${diff}px)`
    }
  })
  // 计算每一组的高度区间
  function calculate () {
    const list = groupRef.value.children
    let height = 0
    const listHeightsVal = listHeights.value
    // listHeightsVal.length = 0
    listHeightsVal.push(height)
    for (let i = 0; i < list.length; i++) {
      height += list[i].clientHeight
      listHeightsVal.push(height)
    }
  }
  function onScroll (position) {
    scrollY.value = -position.y
  }
  return {
    groupRef,
    fixedTitle,
    fixedStyle,
    currentIndex,
    onScroll
  }
}
